package org.liang.family_manager.controller;

import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.liang.family_manager.controller.vo.RegistrationForm;
import org.liang.family_manager.dao.repo.FamilyAdminRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.liang.family_manager.dao.po.FamilyAdmin;
import org.springframework.ui.Model;
@Controller
@AllArgsConstructor
public class AuthController {
    private final FamilyAdminRepository familyAdminRepository;
    private final PasswordEncoder passwordEncoder;

    @GetMapping("/login")
    public String login() {
        return "login";
    }


    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        // 确保总是有registrationForm对象
        if (!model.containsAttribute("registrationForm")) {
            model.addAttribute("registrationForm", new RegistrationForm());
        }
        return "register";
    }


    @PostMapping("/register")
    public String register(@Valid RegistrationForm form, BindingResult result) {
        if (result.hasErrors()) {
            return "register";
        }

        // 检查用户名是否已存在
        if (familyAdminRepository.findByUsername(form.getUsername()).isPresent()) {
            result.rejectValue("username", "error.username", "用户名已存在");
            return "register";
        }

        // 创建并保存管理员账户
        FamilyAdmin admin = new FamilyAdmin();
        admin.setFamilyName(form.getFamilyName());
        admin.setUsername(form.getUsername());
        admin.setPassword(passwordEncoder.encode(form.getPassword()));
        admin.setFamilyDescription(form.getFamilyDescription());

        familyAdminRepository.save(admin);

        return "redirect:/login?registered";
    }
    
    @GetMapping("/dashboard")
    public String dashboard() {
        return "dashboard";
    }
}